import React from 'react';
import { View, Image, SwiperItem, Swiper } from '@tarojs/components';
import execl from '@/public/img/EXCEL.png';
import { gotoPage, Guid } from '@/utils/common';
import './index.scss';

type IData = {
  id?: string;
  route?: string;
  url: string;
  title: string;
};

interface IZbGridProps {
  /**
   * 内容
   */
  data: IData[];
  /**
   * 一行显示多少个
   */
  columnNum?: number;
  /**
   * 类型
   */
  type?: 'square' | 'swiper';
}
const ZbGrid = (props: IZbGridProps) => {
  const { data, type = 'square', columnNum = 4 } = props;

  const [swiperData, setSwiperData] = React.useState<IData[][]>([]);

  React.useEffect(() => {
    if (type === 'swiper') {
      const _swiperData: any = [];
      for (let i = 0; i < data.length; i += 8) {
        const _arr = data.slice(i, i + 8);
        _swiperData.push(_arr);
      }
      setSwiperData([..._swiperData]);
    }
  }, [type, data]);

  const onRoute = (route: string) => {
    if (route) {
      gotoPage(route);
    }
  };

  return (
    <View>
      <View className={`zb-grid grid grid-cols-${columnNum} gap-2`}>
        {type === 'square' &&
          data.map((it: IData) => (
            <View
              key={it.id || Guid()}
              className="text-center"
              onClick={() => {
                onRoute(it?.route || '');
              }}
            >
              <View>
                <Image className="zb-grid-image" mode="widthFix" src={it.url || execl} />
              </View>
              <View className="text-sm">{it.title || '上传题库'}</View>
            </View>
          ))}
      </View>

      {type === 'swiper' && (
        <Swiper className="w-full" circular indicatorDots indicatorColor="#999" indicatorActiveColor="#000">
          {swiperData.map((_data: IData[]) => (
            <SwiperItem className="w-full">
              <View className="w-full grid grid-cols-4 gap-2">
                {_data.map((it: IData) => (
                  <View key={it.id || Guid()} className="text-center">
                    <View>
                      <Image className="zb-grid-image" mode="widthFix" src={it.url || execl} />
                    </View>
                    <View className="text-sm">{it.title || '上传题库'}</View>
                  </View>
                ))}
              </View>
            </SwiperItem>
          ))}
        </Swiper>
      )}
    </View>
  );
};

export default ZbGrid;
